package com.web709.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.web709.common.R;
import com.web709.entity.Product;
import com.web709.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

@RestController
@RequestMapping("/product")
@Slf4j
@Api(tags = "商品管理")
public class ProductController {
    @Autowired
    private ProductService productService;

    //添加商品
    @PostMapping("/addProduct")
    @ApiOperation("添加商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "product", value = "商品信息", required = true, dataType = "Product"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<String> addProduct(@RequestBody Product product) {
        product.setStatus('1');
        boolean save = productService.save(product);
        if (save) {
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    @PostMapping("/updateProduct")
    @ApiOperation("修改商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "product", value = "商品信息", required = true, dataType = "Product"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<String> updateProduct(@RequestBody Product product) {
        final String SUCCESS_MESSAGE = "修改成功";
        final String FAILURE_MESSAGE = "修改失败";
        try {
            boolean update = productService.updateById(product);
            if (update) {
                log.info("产品更新成功: {}", product.getId());
                return R.success(SUCCESS_MESSAGE);
            } else {
                log.warn("产品更新失败: {}", product.getId());
                return R.error(FAILURE_MESSAGE);
            }
        } catch (Exception e) {
            log.error("产品更新时发生异常: {}", e.getMessage(), e);
            return R.error("系统错误，请稍后再试");
        }
    }

    //分页查询商品
    @GetMapping("/page")
    @ApiOperation("分页查询商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<Page<Product>> page(
            @RequestParam @Min(1) int page,
            @RequestParam @Min(1) @Max(100) int pageSize,
            @RequestHeader(required = false) String token) {
        try {
            if (token != null && !token.isEmpty()) {
                // 这里可以添加 token 的进一步验证逻辑
                log.info("Token received: {}", token);
            }
            Page<Product> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.orderByDesc(Product::getId);

            productService.page(pageInfo, queryWrapper);
            log.info("Successfully fetched page {} with size {}", page, pageSize);
            return R.success(pageInfo);
        } catch (Exception e) {
            log.error("Error occurred while fetching product pages", e);
            return R.error("系统内部错误");
        }
    }



    /**
     * 统计商品数量
     *
     * @return 商品总数
     */
    @GetMapping("/count")
    @ApiOperation(value = "统计商品数量", notes = "获取系统中的商品总数")
    public R<Long> count() {
        long count = productService.count();
        return R.success(count);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<String> delete(@PathVariable Integer id) {
        try {
            boolean removed = productService.removeById(id);
            if (removed) {
                log.info("商品删除成功: {}", id);
                return R.success("删除成功");
            } else {
                log.warn("商品删除失败: {}", id);
                return R.error("删除失败");
            }
        } catch (Exception e) {
            log.error("商品删除时发生异常: {}", e.getMessage(), e);
            return R.error("系统错误，请稍后再试");
        }
    }

    @GetMapping("/getProductById/{id}")
    @ApiOperation("根据商品ID查询商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<Product> getProductById(@PathVariable Integer id) {
        Product product = productService.getById(id);
        if (product != null) {
            return R.success(product);
        }
        return R.error("商品不存在");
    }
}
